/*
 * db.java
 *
 * Created on 11 Февраль 2008 г., 23:30
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package xmppbot;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author lian
 */
public class db {
//    Statement statements = null;
    ResultSet result = null;
    Connection mysqlconn = null;
    ArrayList statements = new ArrayList();
    public String hostname,port,database,user,pass;
    /** Creates a new instance of db */
    public db(String hostname, String port, String database, String user, String pass) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException 
    {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        mysqlconn = DriverManager.getConnection("jdbc:mysql://" + hostname + ":" + port + "/" + database + "?user=" + user + "&password=" + pass);
//        statements = mysqlconn.createStatement(result.TYPE_FORWARD_ONLY, result.CONCUR_UPDATABLE);
        this.hostname = hostname;
        this.port = port;
        this.database = database;
        this.user = user;
        this.pass = pass;
    }
    
    public Statement getStatement () {
        Statement st = null;
        try {
            st = mysqlconn.createStatement(result.TYPE_FORWARD_ONLY, result.CONCUR_READ_ONLY);
//            statements.add(st);
        } catch (SQLException ex) {
            try {
                st.close();
            } catch (SQLException exc) {
                exc.printStackTrace();
            }
            reconnect();
            st = getStatement();
        }
        return st;
    }
    
    public void reconnect () {
        try {
            mysqlconn.close();
            mysqlconn = DriverManager.getConnection("jdbc:mysql://" + hostname + ":" + port + "/" + database + "?user=" + user + "&password=" + pass);
        } catch (SQLException ex) {
            ex.printStackTrace();
            reconnect();
        }
    }
    
    public static void killrs (ResultSet rs) throws SQLException {
        if (rs != null) {
            if (rs.getStatement() != null) {
                rs.getStatement().close();
            }
            rs.close();
        }
    }
}
